package org.smart4j.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;

/**
 * 控制器助手类
 * 
 * @author TW
 *
 */
public class ControllerHelper {
	
	private static final Map<Request, Handler> ACTION_MAP = new HashMap<Request, Handler>();

	static {
		//获取所有Controller类
		Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
		if (CollectionUtil.isNotEmpty(controllerClassSet)) {
			for (Class<?> controllerClass : controllerClassSet) {
				//获取该Controller中所有方法
				Method[] methods = controllerClass.getMethods();
				if (ArrayUtil.isNotEmpty(methods)) {
					for (Method method : methods) {
						//判断该方法是否带有Action注解
						if (method.isAnnotationPresent(Action.class)) {
							//从Action注解中获取URL映射规则
							Action action = method.getAnnotation(Action.class);
							String mapping = action.value();
							//验证URL映射规则
							if(mapping.matches("\\w+:/\\w*")){
								String[] array  = mapping.split(":");
								if(ArrayUtil.isNotEmpty(array)&&array.length==2){
									//获取请求方法路径和名称
									String requestMethod = array[0];
									String requestPath = array[1];
									Request request = new Request(requestMethod,requestPath);
									Handler handler = new Handler(controllerClass,method);
									//初始化ActionMap
									ACTION_MAP.put(request, handler);
								}
							}
						}

					}

				}
			}

		}

	}
	/**
	 * 获取Hanlder
	 * @param requestMethod
	 * @param requestPath
	 * @return
	 */
	public static Handler getHandler(String requestMethod,String requestPath){
		Request request = new Request(requestMethod,requestPath);
		return ACTION_MAP.get(request);
	}
}
